package com.ins1st.plus.config.shiro;

import cn.hutool.crypto.SecureUtil;
import com.ins1st.plus.api.system.user.entity.SysUser;
import com.ins1st.plus.api.system.user.service.SysUserApi;
import com.ins1st.plus.util.SpringBeanFactoryUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @program: ins1st-plus
 * @description: shiro认证配置
 * @author: coderSun
 * @create: 2019-09-09 14:52
 **/
public class ShiroRealm extends AuthorizingRealm {


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUserApi sysUserApi = SpringBeanFactoryUtils.getBean("sysUserApi", SysUserApi.class);
        List<String> auths = sysUserApi.queryMenuRolesByUserId(ShiroExt.getUser().getId());
        Set<String> set = new HashSet<>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (String auth : auths) {
            set.add(auth);
        }
        info.setStringPermissions(set);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        SysUserApi sysUserApi = SpringBeanFactoryUtils.getBean("sysUserApi", SysUserApi.class);
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        String userPassword = String.valueOf(token.getPassword());
        if (StringUtils.isBlank(userName)) {
            throw new AuthenticationException("用户名不能为空");
        }
        if (StringUtils.isBlank(userPassword)) {
            throw new AuthenticationException("密码不能为空");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser = sysUserApi.getOne(sysUser);
        if (sysUser == null) {
            throw new AuthenticationException("该账号不存在");
        }
        if (StringUtils.equals(sysUser.getLoginStatus(), "2")) {
            throw new AuthenticationException("该用户已被禁止登入");
        }
        if (!StringUtils.equals(SecureUtil.md5(userName + "-" + userPassword), sysUser.getUserPassword())) {
            throw new AuthenticationException("密码错误");
        }
        return new SimpleAuthenticationInfo(sysUser, userPassword, getName());
    }
}
